package com.yiwei.jmx.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yiwei.jmx.Application;
import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.AddResslistBean;
import com.yiwei.jmx.api.bean.ContractBean;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.info.InfoCallBack;
import com.yiwei.jmx.info.PhoneInfo;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.PreferenceUtils;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.view.CircularProgress;
import com.yiwei.jmx.view.SelectMenuTipsDilaog;
import com.yiwei.jmx.view.V19FrameLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 借款协议界面
 * Created by Master.Dong on 16/4/10.
 */

//@PermissionsRequestSync(permission = {Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS},
//        value = {WRITE_CONTACTS, READ_CONTACTS})
public class LoanAgreementActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;

    @BindView(R.id.about_content)
    TextView aboutContent;
    @BindView(R.id.web_view)
    RelativeLayout webView;
    @BindView(R.id.sv)
    ScrollView sv;
    @BindView(R.id.progressBar)
    CircularProgress loading;
    @BindView(R.id.disagree)
    TextView disagree;
    @BindView(R.id.agree)
    TextView agree;
    @BindView(R.id.btn_view)
    RelativeLayout btnView;
    private List<Map<String, String>> contactList;
    private List<Map<String, String>> callLogList;
    private List<Map<String, String>> appList;
    private List<Map<String, String>> smsList;
    private PhoneInfo phoneInfo;
    //    private WebView webView;
    private WebView mWebView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loan_agreement_activity);
        ButterKnife.bind(this);
        initBar();
        initView();

    }

    private void initView() {
//        datas = getIntent().getParcelableArrayListExtra("loan_steps");
        contactList = new ArrayList<Map<String, String>>();
        callLogList = new ArrayList<Map<String, String>>();
        appList = new ArrayList<Map<String, String>>();
        smsList = new ArrayList<Map<String, String>>();


        phoneInfo = new PhoneInfo(this);  //实例化通讯录


        mWebView = new WebView(Application.getInstance());
        webView.addView(mWebView);


        try {
            String deal_id = UserInfoGlobal.getDealId();
            int type = getIntent().getIntExtra("type", 1);
            if (type == 1) {
                btnView.setVisibility(View.VISIBLE);
                getContract(17 + "", deal_id);
            } else if (type == 2) {
                getContract(17 + "", deal_id);
            } else getContract(0 + "", deal_id);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onBackPressed() {
        showQuitDialog();
    }

    private void showQuitDialog() {
        new SelectMenuTipsDilaog(this).setOnChooseListener(new SelectMenuTipsDilaog.OnChooseListener() {
            @Override
            public void onLeft() {
                finish();
            }

            @Override
            public void onRight() {

            }
        }).showTwoSelectData("主人", R.mipmap.img_idcard_fail_dialog, "如果不签署借款合同，是借不到款的喔", "我要离开", "继续留下").show();
    }

    private void setWebView(String content) {
        webView.setVisibility(View.VISIBLE);

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");

        String html = "<html><head><title>服务协议</title></head><body></body></html>";
        mWebView.loadDataWithBaseURL(html, content + "", "text/html", "utf-8", null);
    }


    /**
     * 获取协议
     */
    private void getContract(String id, String deal_id) {

        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        ContractBean bean = new ContractBean();
        bean.id = id;
        bean.deal_id = deal_id;
        Api.api_service.getContract(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    if (result.getData() != null) {
                        txtTitle.setText(result.getData().getTitle());
                        setWebView(result.getData().getContent());
                    }
                });
    }


    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (loading != null) {
            if (b) {
                agree.setEnabled(false);
                loading.setVisibility(View.VISIBLE);
            } else {
                agree.setEnabled(true);
                loading.setVisibility(View.GONE);
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyWebView();

    }

    public void destroyWebView() {

        webView.removeAllViews();

        if (mWebView != null) {
            mWebView.onPause();
            mWebView.destroy();
            mWebView = null; // Note that mWebView.destroy() and mWebView = null do the exact same thing
        }

    }


  /* -------------  获取手机通讯录，短信，通话记录，应用列表  --------------- */


    /**
     * 上传手机信息
     */
    private void getAddResslist() {
//        if (contactList == null || contactList.size() == 0) {
//            ToastUtil.makeText(this, "获取通讯录为空").show();
//            showDialog("通讯录");
//            showLoading(false);
//            return;
//        }
        phoneInfo.getCallLogList(new InfoCallBack() {
            @Override
            public void onSuccess(final Object o) {
                callLogList = (List<Map<String, String>>) o;
                submitData();
            }

            @Override
            public void onFailure(String cause) {
                submitData();
            }
        });


    }

    private void submitData() {
        addResslist(PreferenceUtils.getString(this, "deal_id", ""), contactList, callLogList, appList, smsList);
    }

    /**
     * 获取通讯录
     */
    private void checkContactsPermission() {
        //判断是否6.0
//        Permissions4M
//                .get(LoanAgreementActivity.this)
//                .requestSync();

        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                showLoading(true);
                phoneInfo.getContactsList(new InfoCallBack() {
                    @Override
                    public void onSuccess(final Object o) {
                        contactList = (List<Map<String, String>>) o;
//                        checkCallPermission();
                        getAppList();
                    }

                    @Override
                    public void onFailure(String cause) {
//                            checkCallPermission();
//                            goAppDetailSettingIntent(LoanAgreementActivity.this);
//                            Toast.makeText(LoanAgreementActivity.this, "获取联系人权限被拒，请到设置里设为允许", Toast.LENGTH_LONG).show();
                        getAppList();
//                        showDialog("联系人");
//                        showLoading(false);
                    }
                });
            }

            @Override
            public void onReject() {

            }
        }, R.string.contact_p_v2, R.string.get_contact_v2, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS, Manifest.permission.READ_CALL_LOG);
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
//            grantResults) {
//        Permissions4M.onRequestPermissionsResult(this, requestCode, grantResults);
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//    }

    private void showDialog(String permission) {
        Activity activity = LoanAgreementActivity.this;
        while (activity.getParent() != null) {
            activity = activity.getParent();
        }
        try {
            Dialog.showDefaultDialog(this, "提示", "请到设置中心开启找花花的" + permission + "权限", getResources().getString(R.string.cancel), "前往设置", true, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    goAppDetailSettingIntent(LoanAgreementActivity.this);
                }

                @Override
                public void cancel() {

                }
            });
        } catch (Exception e) {
            Log.d("d", "AlertDialog  Exception:" + e.getMessage());
        }
    }

    public void goAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(localIntent);
    }


    /**
     * 获取app列表
     */
    private void getAppList() {
        phoneInfo.getAppList(new InfoCallBack() {
            @Override
            public void onSuccess(final Object o) {
                appList = (List<Map<String, String>>) o;
                getSmsList();
//                getAddResslist();
            }

            @Override
            public void onFailure(String cause) {
//                getAddResslist();
                getSmsList();
            }
        });
    }

    /**
     * 获取短信列表
     */
    private void getSmsList() {
        phoneInfo.getSmsList(new InfoCallBack() {
            @Override
            public void onSuccess(final Object o) {
                smsList = (List<Map<String, String>>) o;
                getAddResslist();
            }

            @Override
            public void onFailure(String cause) {
                getAddResslist();
            }
        });
    }


    public void addResslist(String deal_id, List<Map<String, String>> contactList, List<Map<String, String>> callLogList, List<Map<String, String>> appList, List<Map<String, String>> smsList) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loading.setVisibility(View.VISIBLE);
        AddResslistBean item = new AddResslistBean();
        item.addresslist = contactList;
        item.app_list = appList;
        item.phone_call_records = callLogList;
        item.deal_id = deal_id;
        item.sms = smsList;
        Api.api_service.getAddResslistInfo(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loading.setVisibility(View.GONE);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Intent intent = new Intent(this, FaceIdentityZhiMaActivity.class);
                    intent.putExtra("isFromLoan", true);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    LoanAgreementActivity.this.finish();
                });
    }

    @OnClick({R.id.btn_back, R.id.disagree, R.id.agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.disagree:
                showQuitDialog();
                break;
            case R.id.agree:
                checkContactsPermission();
                break;
        }
    }
}
